package com.blb.util;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/*
* 解析地址获取经纬度
* */
@Component
public class AddressLngLatExchange {

    public String getLngLat(String address) {
        StringBuffer json = new StringBuffer();
        try {
            URL u = new URL("http://restapi.amap.com/v3/geocode/geo?address="+address+"&output=JSON&key=73d03800ae99b821e63192b5b4b80276");
            URLConnection yc = u.openConnection();
            //读取返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));
            String inputline = null;
            while((inputline=in.readLine())!=null){
                json.append(inputline);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jsonStr=json.toString();
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        System.out.println("jsonObject = " + jsonObject);
        //判断输入的位置点是否存在
        if(jsonObject.getJSONArray("geocodes").size()>0)
            return jsonObject.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
        else
            return null;
    }


}